package com.umeox.watch.moto.dataservice.db;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.umeox.moto.common.log.Logger;
import com.umeox.watch.moto.dataservice.base.BaseApp;
import com.umeox.watch.moto.dataservice.db.model.ContactInfo;

import java.util.List;

public class ThirdPartyDataBaseUtils {
    private static final String TAG = "ThirdPartyDataBaseUtils";

    public static void deletePhoneContacts(List<ContactInfo> contactInfos) {
        for (ContactInfo contactInfo : contactInfos) {
            Logger.d(TAG, "deletePhoneContacts: " + contactInfo.toString());
            deletePhoneContactByRawId(contactInfo.getRawContactId());
        }
    }

    public static void savePhoneContacts(List<ContactInfo> contactInfos) {
        for (ContactInfo contactInfo : contactInfos) {
            long rawContactId = contactInfo.getRawContactId() > 0 ? contactInfo.getRawContactId() : getRawContactId(TextUtils.isEmpty(contactInfo.getPhone()) ? "123456" : contactInfo.getPhone());
            if (existPhoneContact(rawContactId)) {
                updatePhoneContact(contactInfo);
            } else {
                insertPhoneContact(contactInfo);
            }
        }
    }

    public static long getRawContactId(String phone) {
        long rawContactId = -1;

        Uri uriNumber2Contacts = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, phone);
        // 查询Uri，返回数据集
        Cursor cursor = getContentResolver().query(uriNumber2Contacts, null, null, null, null);
        try {
            if (cursor != null && cursor.moveToNext()) {
                rawContactId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
            }
        } catch (Exception ignored) {
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return rawContactId;
    }


    public static boolean existPhoneContact(long rawContactId) {
        boolean exists = false;
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID + "=" + rawContactId, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            exists = true;
        }
        if (cursor != null) {
            cursor.close();
        }
        return exists;
    }


    public static void insertPhoneContact(@NonNull ContactInfo contactInfo) {

        ContentValues values = new ContentValues();
        // 下面的操作会根据RawContacts表中已有的rawContactId使用情况自动生成新联系人的rawContactId
        Uri rawContactUri = getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, values);
        long rawContactId = ContentUris.parseId(rawContactUri);
        contactInfo.setRawContactId(rawContactId);

        values.clear();
        values.put(ContactsContract.RawContacts._ID, rawContactId);
        values.put(ContactsContract.Contacts.DISPLAY_NAME, contactInfo.getName());
        getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, values);

        //往data表入姓名数据
        values.clear();
        values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);//内容类型
        values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, contactInfo.getName());
        Uri rcUri = getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);

        if (rcUri != null) {
            //往data表入电话数据
            values.clear();
            values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
            values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
            values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, contactInfo.getPhone());
            values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE);
            getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
        }
    }


    public static void updatePhoneContact(@NonNull ContactInfo contactInfo) {
        ContentResolver contentResolver = getContentResolver();
        ContentValues values = new ContentValues();
        //修改显示的联系人名称字段

        values.clear();
        values.put(ContactsContract.Contacts.DISPLAY_NAME, contactInfo.getName());
        contentResolver.update(ContactsContract.RawContacts.CONTENT_URI, values, ContactsContract.Contacts._ID + "=?", new String[]{contactInfo.getRawContactId() + ""});


        // 更新Data表电话号码
        values.clear();
        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, contactInfo.getPhone());
        contentResolver.update(ContactsContract.Data.CONTENT_URI, values, ContactsContract.Data.MIMETYPE + "=? and " + ContactsContract.Data.RAW_CONTACT_ID + "=?",
                new String[]{ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, contactInfo.getRawContactId() + ""});
        // 更新Data表联系人姓名
        values.clear();
        values.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, contactInfo.getName());
        values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, contactInfo.getName());
        contentResolver.update(ContactsContract.Data.CONTENT_URI, values, ContactsContract.Data.MIMETYPE + "=? and " + ContactsContract.Data.RAW_CONTACT_ID + "=?",
                new String[]{ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE, contactInfo.getRawContactId() + ""});
    }


    public static void deletePhoneContactByRawId(long rawContactId) {
        Logger.i(TAG, "deletePhoneContactByRawId: " + rawContactId);

        ContentResolver contentResolver = getContentResolver();
        //删除rawContact表中数据
        Uri uri = Uri.parse(ContactsContract.RawContacts.CONTENT_URI.toString() + "?" + ContactsContract.CALLER_IS_SYNCADAPTER + "=true");
        uri = ContentUris.withAppendedId(uri, rawContactId);
        contentResolver.delete(uri, null, null);

        uri = Uri.parse(ContactsContract.Data.CONTENT_URI.toString() + "?" + ContactsContract.CALLER_IS_SYNCADAPTER + "=true");
        uri = ContentUris.withAppendedId(uri, rawContactId);
        contentResolver.delete(uri, null, null);

        uri = Uri.parse(ContactsContract.Groups.CONTENT_URI.toString() + "?" + ContactsContract.CALLER_IS_SYNCADAPTER + "=true");
        uri = ContentUris.withAppendedId(uri, rawContactId);
        contentResolver.delete(uri, null, null);
    }

    private static ContentResolver getContentResolver() {
        return BaseApp.getInstance().getContentResolver();
    }

}
